﻿using System;
using System.Collections.Generic;
using System.Dynamic;
using System.Reflection;

namespace CI.Models.Data
{
    public class DynamicBase : DynamicObject
    {
        private readonly Dictionary<string, object> _mapping = new Dictionary<string, object>();

        public override bool TryGetMember(GetMemberBinder binder, out object result)
        {
            result = GetValue(binder.Name);
            return true;
        }

        public override bool TrySetMember(SetMemberBinder binder, object value)
        {
            SetValue(binder.Name, value);
            return true;
        }

        public void SetValue(string memberName, object value)
        {
            if (_mapping.ContainsKey(memberName)) _mapping[memberName] = value;
            else _mapping.Add(memberName, value);
        }

        public object GetValue(string memberName)
        {
            return _mapping.ContainsKey(memberName) ? _mapping[memberName] : null;
        }

        public Type GetMemberType(string memberName)
        {
            PropertyInfo possiblePropertyInfo = GetType().GetProperty(memberName);

            return possiblePropertyInfo != null ? possiblePropertyInfo.PropertyType : GetValue(memberName).GetType();
        }
    }
}